<?php

namespace App\CustHub\Listener;

use App\Common\Robot\Robot;
use App\CustHub\Event\RobotInfoChange;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChRobot;
use App\Robot\Service\RobotApiService;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;

#[Listener]
class RobotInfoChangeListener implements ListenerInterface
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            RobotInfoChange::class,
        ];
    }

    public function process(object $event): void
    {
        $robot  = $event->robot;

        $robotApiService = make(Robot::class, [$robot->server_id, $robot->uuid])->gateway();
        $rst = $robotApiService->getProfile();
        if($rst !== false){
            $robotInfo = $rst;
            stdout_log()->info('机器人信息'.json_encode($robotInfo,JSON_UNESCAPED_UNICODE));
            ChRobot::query()
                ->where('id', $robot->id)
                ->update([
                    'acctid' => $robotInfo['acctid'] ?? '',
                    'gender' => $robotInfo['gender'],
                    'mobile' => $robotInfo['mobile'],
                    'nickname' => $robotInfo['nickname'],
                    'alias' => $robotInfo['alias'],
                    'real_name' => $robotInfo['real_name'],
                    'avatar' => $robotInfo['avatar_url']
                ]);
            $this->container->get(ChRobotMapper::class)->clearCache($robot->id,$robot->uuid);
        }
    }

}